package com.gr.staffpm.pages.tasks;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.IAjaxCallDecorator;
import org.apache.wicket.ajax.calldecorator.AjaxCallDecorator;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.TextArea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class CommentFormAjaxSubmitBehavior extends AjaxFormSubmitBehavior {

    private static final long serialVersionUID = 1L;
    private final TextArea<String> comment;
    private final WebMarkupContainer commentsContainer;
    Logger log = LoggerFactory.getLogger(getClass());

    public CommentFormAjaxSubmitBehavior(CommentForm form, WebMarkupContainer commentsContainer) {
        super(form, "onsubmit");
        this.commentsContainer = commentsContainer;
        comment = form.getCommentBox();
    }

    @Override
    protected IAjaxCallDecorator getAjaxCallDecorator() {
        return new AjaxCallDecorator() {

            private static final long serialVersionUID = 1L;

            @Override
            public CharSequence decorateScript(CharSequence script) {
                return script + "return false;";
            }
        };
    }

    @Override
    protected void onSubmit(AjaxRequestTarget target) {
        // add the list of components that need to be updated
        while (target.getComponents().iterator().hasNext()) {
            log.info("Update: " + target.getComponents().iterator().next());
        }
        target.addComponent(commentsContainer);
        target.addComponent(comment);
    }

    @Override
    protected void onError(AjaxRequestTarget target) {
        log.error("Error in ajax form request.");
    }
}
